package com.jingbian.cppccbackend.service.impl.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jingbian.cppccbackend.entity.ActivitiesApply;

import com.jingbian.cppccbackend.mapper.user.ActivitiesApplyMapper;
import com.jingbian.cppccbackend.service.user.IActivitiesApplyService;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import com.jingbian.cppccbackend.vo.ActivityApplyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pum
 * @since 2025-02-28
 */
@Service
public class ActivitiesApplyServiceImpl extends ServiceImpl<ActivitiesApplyMapper, ActivitiesApply> implements IActivitiesApplyService {
  @Autowired
  private ActivitiesApplyMapper activitiesApplyMapper;

  @Override
  public PageInfo<ActivityApplyVO> getApplyList(int aid, int pageNum) {

    // 开启分页
    PageHelper.startPage(pageNum, 10);
    List<ActivityApplyVO> list = activitiesApplyMapper.getApplyList(aid);

    // 将结果封装成PageInfo对象
    return new PageInfo<>(list);
  }

  @Override
  public boolean joinActivity(Integer aid) {
    ActivitiesApply activitiesApply = new ActivitiesApply();

    activitiesApply.setAid(aid);
    Map<String,Object> claims = ThreadLocalUtil.get();
    Integer userId = (Integer) claims.get("uid");
    // 查询是否已报名
    boolean exists = activitiesApplyMapper.existsByAidAndApplyId(aid, userId);
    if (exists) {
      return false;
    }
    activitiesApply.setApplyId(userId);
    activitiesApply.setApplyDate(LocalDateTime.now());
    activitiesApplyMapper.insert(activitiesApply);
    return true;
  }

  @Override
  public void deleteJoinActivity(Integer aid) {
    Map<String,Object> claims = ThreadLocalUtil.get();
    Integer userId = (Integer) claims.get("uid");
    LambdaQueryWrapper<ActivitiesApply> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(ActivitiesApply::getAid, aid)
        .eq(ActivitiesApply::getApplyId, userId);
    activitiesApplyMapper.delete(wrapper);
  }
}
